package com.example.ipcserver.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import com.example.hand_write_ipc.BookManager;
import com.example.hand_write_ipc.IBookListener;
import com.example.ipc.Book;

import java.util.ArrayList;
import java.util.List;

public class BinderService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return mBookManager;
    }

    private final List<Book> mBooks = new ArrayList<>();

    private IBookListener mBookListener;

    @Override
    public void onCreate() {
        super.onCreate();
        mBooks.add(new Book("Java,从入门到精通"));
        mBooks.add(new Book("Android,从入门到放弃"));
        mBooks.add(new Book("Android Studio"));
        mBooks.add(new Book("Android,从放弃到突破"));
    }

    private BookManager mBookManager = new BookManager() {

        @Override
        public List<Book> getBookList() throws RemoteException {
            return mBooks;
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            mBooks.add(book);
            simulateNewBookArrival();
        }

        @Override
        public void addBookListener(IBookListener listener) throws RemoteException {
            mBookListener = listener;
        }
    };

    private void simulateNewBookArrival() {
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    int random = (int) (Math.random() * 1000);
                    Book book = new Book("这是一本新书:" + random);
                    mBooks.add(book);
                    mBookListener.onNewBookArrival(book);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

}
